﻿using EmguFFmpeg;
using FFmpegScreenCapture.Properties;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace FFmpegScreenCapture
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private WriteableBitmap writeableBitmap;
        private ManualResetEventSlim manualResetEventSlim = new ManualResetEventSlim(true);

        public MainWindow()
        {
            InitializeComponent();
            FFmpegHelper.RegisterBinaries("./FFmpeg");
        }

        private void ToggleButton_Click(object sender, RoutedEventArgs e)
        {
            Settings.Default.Save();
            bool? isChecked = (sender as ToggleButton).IsChecked;
            if (isChecked.HasValue && isChecked.Value)
            {
                manualResetEventSlim.Reset();
                Task.Run(RtmpFunc);
            }
            else
            {
                manualResetEventSlim.Set();
            }
        }

        private void RtmpFunc()
        {
            MediaDevice.InitializeDevice();

            using (MediaReader reader = new MediaReader("video=\"screen-capture-recorder\"", new InFormat("dshow")))
            using (MediaWriter writer = new MediaWriter("output.mp4"))
            {
                foreach (var stream in reader)
                    writer.AddStream(stream);
                writer.Initialize();

                PixelConverter converter = new PixelConverter(writer[0].Codec);
                long pts = 0;
                foreach (var packet in reader.ReadPacket())
                {
                    foreach (var frame in writer[0].ReadFrame(packet))
                    {
                        foreach (var dstframe in converter.Convert(frame))
                        {
                            dstframe.Pts = pts++;
                            foreach (var dstpacket in writer[0].WriteFrame(dstframe))
                            {
                                writer.WritePacket(dstpacket);
                            }
                        }
                    }
                    if (manualResetEventSlim.IsSet)
                        break;
                }
                writer.FlushMuxer();
            }
        }
    }
}